package bll

import (
	"context"
	"encoding/json"
	"fmt"
	"maya-service/constant"
	"maya-service/model"
	"maya-service/model/po"
	"maya-service/store/redis"
	"maya-service/utils"
)

func RemoveSupervisorData(userId string) error {
	return redis.KV.HDel(context.Background(), fmt.Sprintf("supervisor"), userId).Err()
}

// CacheSupervisorData 缓存督导师列表
func CacheSupervisorData(level int, userIds []string) error {
	args := []interface{}{}
	for _, v := range userIds {
		args = append(args, v, level)
	}
	if len(args) == 0 {
		return nil
	}
	// 删除当前所有督导师缓存
	redis.KV.HDel(context.Background(), fmt.Sprintf("supervisor"))
	// 建立缓存
	return redis.KV.HMSet(context.Background(), fmt.Sprintf("supervisor"), args...).Err()
}

func GetSupervisorData(userId string) (string, error) {
	return redis.KV.HGet(context.Background(), "supervisor", userId).Result()
}

// GetSuperVisorList 获取督导师列表
func GetSuperVisorList(levels []int) (userList []string) {
	userMap, _ := redis.KV.HGetAll(context.Background(), "supervisor").Result()
	if len(userMap) == 0 {
		return
	}

	levelMap := make(map[int]struct{})
	for _, v := range levels {
		levelMap[v] = struct{}{}
	}

	for k, v := range userMap {
		if _, ok := levelMap[int(utils.StrToInt64(v))]; ok {
			userList = append(userList, k)
		}
	}
	return
}

func GetSupervisorLevelByOrderNo(orderNo string) int {
	orderInfo, _ := Order.Find(context.Background(), &model.OrderInfoRequest{OrderNo: orderNo})
	if orderInfo == nil || orderInfo.Id <= 0 {
		return 1
	}

	data := po.OrderContext{}
	_ = json.Unmarshal([]byte(orderInfo.OrderContext), &data)
	return data.Goods.ProductType
}

func GetKfIdByOrder(orderNo string) string {
	orderInfo, _ := Order.Find(context.Background(), &model.OrderInfoRequest{OrderNo: orderNo})
	if orderInfo == nil || orderInfo.Id <= 0 {
		return ""
	}

	data := po.OrderContext{}
	_ = json.Unmarshal([]byte(orderInfo.OrderContext), &data)
	return constant.GetKfId(data.Goods.ProductType)
}
